package controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbms.Postgres;

import model.Anagrafica;
import model.Utente;

/**
 * Servlet implementation class AdminPanelUser
 */
@WebServlet("/AdminPanelUser")
public class AdminPanelUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminPanelUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Utente utente = (Utente) request.getSession().getAttribute("utente");
		int id = utente.getId();
		
		ResultSet rs = Postgres.getInstance().getAnagraficaById(id);
		try {
			rs.next();
			
			Anagrafica bean = new Anagrafica();
			bean.setCogn(rs.getString("cognome"));
			bean.setNome(rs.getString("nome"));
			bean.setId(Integer.parseInt(rs.getString("id")));
			bean.setInd(rs.getString("ind"));
			bean.setSesso(rs.getString("sesso").charAt(0));
			
			if (request.getParameter("modifica") != null) {
				response.sendRedirect("vis.jsp");
			} else if (request.getParameter("elimina") != null) {
				if (Postgres.getInstance().deleteAnagraficaById(bean.getId())) {
					ServletContext sc = getServletContext();
					RequestDispatcher rd = sc.getRequestDispatcher("/QueryServlet");
					rd.forward(request, response);
				}
			} else {
				response.sendRedirect("errore.html");
			}
		} catch (SQLException e) { e.printStackTrace();
		} finally { Postgres.getInstance().closeStatement(); }
		
	}

}
